﻿//-----------------------------------------------------------------------
// <copyright file="ContextManager.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: ContextManager.cs
// * history : created by qinchaoyue 2017-11-28 01:11:42
// </copyright>
//-----------------------------------------------------------------------

namespace Slwy.Context
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// 上下文管理器
    /// </summary>
    public static class ContextManager
    {
        /// <summary>
        /// 自动删除上下文内容
        /// 由框架自动调用
        /// </summary>
        public static void AutoDelete()
        {
            var deleteKeys = new List<string>();
            foreach (var currentKey in SlwyContext.Current.Keys)
            {
                if (currentKey.ToUpper().IndexOf("AUTODELETE", StringComparison.Ordinal) != -1)
                {
                    deleteKeys.Add(currentKey);
                }
            }

            deleteKeys.ForEach(m => SlwyContext.Current.Remove(m));
        }

        /// <summary>
        /// 设置本次请求的上下文变量
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public static void SetThisValue(string key, object value)
        {
            SlwyContext.Current[$"AutoDelete_{SlwyContext.Current.Operator.KeyId}_{key}"] = value;
        }

        /// <summary>
        /// 获取本次请求的上下文变量
        /// 有可能返回 null 请做好判断
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        public static object GetThisValue(string key)
        {
            return SlwyContext.Current.TryGetValue($"AutoDelete_{SlwyContext.Current.Operator.KeyId}_{key}", out var v) ? v : null;
        }
    }
}
